#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project ：python_learning 
@File ：visual_interface_integration.py
@IDE  ：PyCharm 
@Author ：李涵彬
@Date ：2025/2/14 上午9:23 
"""

import sys
import multiprocessing
import time
from multiprocessing import Process

from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QTextEdit, QVBoxLayout, QWidget

from 进程通讯.multi_process_complete_tasks import data_reader, task_processor


# 主界面
class MainWindow(QMainWindow):
	def __init__(self, data_queue, task_queue):
		super().__init__()
		self.data_queue = data_queue
		self.task_queue = task_queue
		self.log = QTextEdit()
		self.setCentralWidget(self.log)
		self.init_ui()

	def init_ui(self):
		self.setWindowTitle("Automation System")
		self.setGeometry(100, 100, 400, 300)
		layout = QVBoxLayout()
		self.log.setReadOnly(True)
		button_db = QPushButton("Update Database")
		button_tcp = QPushButton("Send TCP Message")
		button_db.clicked.connect(self.on_update_db)
		button_tcp.clicked.connect(self.on_send_tcp)
		layout.addWidget(button_db)
		layout.addWidget(button_tcp)
		layout.addWidget(self.log)
		container = QWidget()
		container.setLayout(layout)
		self.setCentralWidget(container)

	def on_update_db(self):
		self.task_queue.put({"type": "update_db", "key": 1, "value": "New Value"})

	def on_send_tcp(self):
		self.task_queue.put({"type": "send_tcp", "message": "Hello"})

	def update_log(self, message):
		self.log.append(message)


# 可视化主进程
def gui_process(data_queue, task_queue):
	app = QApplication(sys.argv)
	window = MainWindow(data_queue, task_queue)
	window.show()

	# 定期检查数据读取
	def check_data():
		if not data_queue.empty():
			data = data_queue.get()
			window.update_log(f"Received data: {data}")
		app.processEvents()
		app.processEvents()  # 调用两次以确保更新
		app.processEvents()  # 调用两次以确保更新
		app.processEvents()  # 调用两次以确保更新

	while True:
		check_data()
		time.sleep(0.1)


# 主入口
def main():
	data_queue = multiprocessing.Queue()
	task_queue = multiprocessing.Queue()

	# 启动数据读取和任务处理进程
	data_reader_process = Process(target=data_reader, args=(data_queue, "example.db"))
	data_reader_process.start()
	task_processor_process = Process(target=task_processor, args=(task_queue, "example.db"))
	task_processor_process.start()

	# 启动 GUI 进程
	gui_process(data_queue, task_queue)


if __name__ == "__main__":
	main()
